$(function() {
	//显示菜单信息
	var head = $("#breadcrumbs");
	head.html('<ul class="breadcrumb">' +
		'<li><i class="icon-home"></i> <a href="/">首页</a><span class="divider"><i class="icon-angle-right"></i></span></li>' +
		'<li><a href="#">绩效管理</a> <span class="divider"><i class="icon-angle-right"></i></span></li>' +
		'<li><a href="/performanceAudit">绩效考核</a><span class="divider"><i class="icon-angle-right"></i></span></li>' +
		'<li class="active">员工绩效审核</li></ul>');
	var delTermArr = []; //需要删除的加分项的id

	var http = new XMLHttpRequest;
	http.open("HEAD", ".", false);
	http.send(null);
	var today = new Date(http.getResponseHeader("Date"));
	var year_today = today.getFullYear();
	var month_today = (today.getMonth() + 1) < 10 ? "0" + (today.getMonth() + 1) : (today.getMonth() + 1);
	var day = today.getDate() < 10 ? "0" + today.getDate() : today.getDate();
	if (day < 23 || day > 26) {
		// $("#saveBtn").css("display", "none");
		// $("#tip").html("<div class='alert' style='margin-bottom:-10px; font-size:18px;'>每月得23-26号才能够审核员工绩效</div>");
		$.ajax({
			url: '/api/item/access',
			type: 'get',
			data: {'_t':new Date().getTime()},
			success: function(accessData) {
				// console.info("------------",result);
				var flag = false;
				$.each(accessData, function(i, access) {
					if(access.showValue == "审核" && access.value == "true") {
						$("#saveBtn").css("display", "block");
						$("#count").css("display", "block");
						$("#tip").html("");
						flag = true;
					}
				});
				if(!flag) {
					$("#saveBtn").css("display", "none");
					$("#count").css("display", "none");
					$("#tip").html("<div class='alert' style='margin-bottom:-10px; font-size:18px;'>每月得23-26号才能够审核员工绩效</div>");
				}
			}
		});
		// window.location.href = "/performanceAudit";
		
	}else{
		$("#saveBtn").css("display", "block");
		$("#count").css("display", "block");
		$("#tip").html("");
		flag = true;

		$("#saveBtn").css("display", "block");
	}

	//加分项增行、删行
	document.onclick = function(evt) {
		var event = evt || window.event;
		var obj = event.srcElement || event.target;
		if (obj.id == "pluse_deleteIcon") {
			obj = obj.parentNode.parentNode;

			if (navigator.userAgent.indexOf("MSIE") > 0) {
				obj.removeNode(true);
			} else if (isFirefox = navigator.userAgent.indexOf("Firefox") > 0) {
				obj.parentNode.removeChild(obj);
			} else {
				obj.remove();
			}
		}
	}
	$("#pluse_btnadd").click(function() {

		var template = "<tr><td class='span3' style='text-align:center;width:40%;word-wrap:break-word; vertical-align:middle;'>" +
			"<input type='text' id='pluse_term' name='pluse_term'  class='perAdd-input' onfocus=\"javascript:this.style.background='#FFFFFF';\" onblur=\"javascript:this.style.background='transparent';\"/></td>" +
			"<td class='span3' style='text-align:center;width:40%;word-wrap:break-word; vertical-align:middle;'>" +
			"<input type='text' id='pluse_content' name='pluse_content'  class='perAdd-input'  onfocus=\"javascript:this.style.background='#FFFFFF';\" onblur=\"javascript:this.style.background='transparent';\"/></td>" +
			"<td class='span2 hidden-480' style='text-align:center;width:10%;word-wrap:break-word; vertical-align:middle;'>" +
			"<input type='text' id='pluse_score' name='pluse_score'  class='perAdd-input'onfocus=\"javascript:this.style.background='#FFFFFF';\" onblur=\"javascript:this.style.background='transparent';\" /></td>" +
			"<td class='span2' style='text-align:center;width:10%;word-wrap:break-word; vertical-align:middle;'>" +
			"<i style='cursor:pointer;' id='pluse_deleteIcon' name='pluse_deleteIcon' class='icon-trash  bigger-150'></i></td></tr>";
		// alert(tr_html);
		// var $html = $(Mustache.to_html(template, null));
		$("#tbd_pluse").append(template);
		// document.onclick = function() {
		// 	var obj = event.srcElement;
		// 	if (obj.id == "pluse_deleteIcon") {
		// 		obj = obj.parentNode.parentNode;
		// 		obj.remove();
		// 	}
		// }
		document.onclick = function(evt) {
			var event = evt || window.event;
			var obj = event.srcElement || event.target;
			if (obj.id == "pluse_deleteIcon") {
				obj = obj.parentNode.parentNode;

				if (navigator.userAgent.indexOf("MSIE") > 0) {
					obj.removeNode(true);
				} else if (isFirefox = navigator.userAgent.indexOf("Firefox") > 0) {
					obj.parentNode.removeChild(obj);
				} else {
					obj.remove();
				}
			}
		}
	});
	//点击返回按钮
	$("#goBack").click(function() {
		var hisPage = $("#hisPage").val();
		window.location.href = "/performanceAudit?hisPage=" + hisPage;
		// window.history.back();
	});
	// document.onclick = function() {
	// 	var obj = event.srcElement;
	// 	if (obj.id == "pluse_deleteIcon") {
	// 		obj = obj.parentNode.parentNode;
	// 		obj.remove();
	// 	}
	// }
	//内容及标准项增行、删行
	// $("#professional_btnadd").click(function() {

	// 	var template = "<tr><td class='span3' style='text-align:center;width:30%;word-wrap:break-word;'>"+
	// 					"<input type='text' id='professional_term' name='professional_term'  class='perAdd-input'onfocus=\"javascript:this.style.background='#FFFFFF';\" onblur=\"javascript:this.style.background='transparent';\"/></td>"+
	// 					"<td class='span3' style='text-align:center;width:10%;word-wrap:break-word;'>"+
	// 					"<input type='text' id='professional_weight' name='professional_weight'  class='perAdd-input'  onfocus=\"javascript:this.style.background='#FFFFFF';\" onblur=\"javascript:this.style.background='transparent';\"/></td>"+
	//                        "<td class='span2 hidden-480' style='text-align:center;width:40%;word-wrap:break-word;'>"+
	// 					"<input type='text' id='professional_completion' name='professional_completion'  class='perAdd-input'onfocus=\"javascript:this.style.background='#FFFFFF';\" onblur=\"javascript:this.style.background='transparent';\" /></td>"+
	// 					"<td class='span2 hidden-480' style='text-align:center;width:10%;word-wrap:break-word;'>"+
	// 					"<input type='text' id='professional_score' name='professional_score'  class='perAdd-input'onfocus=\"javascript:this.style.background='#FFFFFF';\" onblur=\"javascript:this.style.background='transparent';\" /></td>"+
	//                        "<td class='span2' style='text-align:center;width:10%;word-wrap:break-word;'>"+
	// 					"<i id='professional_deleteIcon' name='professional_deleteIcon' class='icon-trash  bigger-150'></i></td></tr>";
	//     // alert(tr_html);
	//     // var $html = $(Mustache.to_html(template, null));
	//     $("#tbd_professional").append(template);
	//     document.onclick = function() {
	//     	var obj = event.srcElement;
	//     	// console.info(obj.id);
	//     	if(obj.id == "professional_deleteIcon") {
	//     		obj = obj.parentNode.parentNode;
	//     		// console.log(obj);
	//     		obj.remove();
	//     	}
	//     }
	// });

	var flag = false; //标志内容及标准是否显示
	var empId = $("#getEmpId").val(); //当前登录用户员工id

	var init = function() {
		var perfId = $("#getPerfId").val();
		var termState = $("#termState").val();
		// console.info("perfId=" + perfId);
		$.ajax({
			url: '/api/performance/selPerfById/' + perfId + '?',
			type: 'get',
			data: {'_t': new Date().getTime()},
			success: function(data) {
				// console.info(data);
				$("#perfState").val(data.perfData.state);
				if (data != null && data.perfData != null && data.perfData.length != 0) {
					var time_today = year_today + "-" + month_today;
					var perfData = data.perfData;
					var termsData = data.termsData;
					if (perfData.perfDate == time_today) {
						// var perfData = data.perfData;
						// var termsData = data.termsData;
						$("#perfDate").val(perfData.perfDate);
						$("#employee").val(perfData.empName);
						$("#employeeid").val(perfData.employeeId);
						if (perfData.comment != null && perfData.comment != "" && termState == 0) {
							$("#tip").html("<div class='alert' style='margin-bottom:-10px; font-size:18px;'>" + perfData.comment + "，请重新审核</div>");

						}
						if (perfData.assessmentPersonId == empId) {
							flag = true;
							//显示职业化评价表
							$("#prefosessonalTab").css("display", "block");
						}

						getOrgParents(perfData.departmentId, 0);
						if (perfData.preDeptId != null && perfData.preDeptId != 0) {
							$("#preDeptId").val(perfData.preDeptId);
							getOrgParents(perfData.preDeptId, 1)
						}
						if (perfData.project != null && perfData.project != 0) {
							$("#project").val(perfData.project);
						}
						showTerms(termsData, perfData.state);
					} else {
						var hisPage = $("#hisPage").val();
						window.location.href = "/performanceAudit?hisPage=" + hisPage;
						// window.location.href = "/performanceAudit";
					}

				} else {
					return;
				}

			}
		});

	};


	init();
	var showTerms = function(termsData, perfState) {
		if (termsData != null && termsData.length != 0) {
			$("#tbd_task").html('');
			// if(perfState == 1) {
			// 	$("#tbd_pluse").html('');
			// 	$("#tbd_professional").html('');
			// }
			var plusFlag = false;
			var prefosessonalFlag = false;
			$.each(termsData, function(i, item) {
				if (item.type == 1) {
					plusFlag = true;
				}
				if (item.type == 2) {
					prefosessonalFlag = true;
				}
			});
			if (prefosessonalFlag) {
				$("#tbd_professional").html('');
			}
			if (plusFlag) {
				$("#tbd_pluse").html('');
			}

			$.each(termsData, function(i, item) {
				// console.info(i + "-----", item.completion);
				var templateData = {
					term: item.term,
					termId: item.id,
					content: item.content,
					weight: item.weight + "%",
					completion: item.completion,
					score: item.score
				};
				var template;
				if (item.type == 0) {
					//工作事项

					template = "<tr><input type='hidden' id=termId name=termId value='{{termId}}'><td class=span3 style='width:20%;word-wrap:break-word;vertical-align:middle; text-align:center' id=term name=term>{{term}}</td>" +
						"<td class='span3' style='width:30%;word-wrap:break-word;vertical-align:middle; text-align:center' id=content name=content>{{content}}</td>" +
						"<td class='span2 hidden-480' style='width:10%;word-wrap:break-word;vertical-align:middle; text-align:center' id=weight name=weight>{{weight}}</td>" +
						"<td class='span3 hidden-phone' style='width:30%;word-wrap:break-word;vertical-align:middle; text-align:center'><input type='text' id='completion' name='completion' class='perAdd-input'  onfocus=\"javascript:this.style.background='#FFFFFF';\" onblur=\"javascript:this.style.background='transparent';\" value='{{completion}}' ></td>" +
						"<td class='span2 hidden-480' style='width:10%;word-wrap:break-word;vertical-align:middle; text-align:center'><input type='text' id='score' name='score'  class='perAdd-input' onfocus=\"javascript:this.style.background='#FFFFFF';\" onblur=\"javascript:this.style.background='transparent';\" value='{{score}}'></td></tr>"
					var $html = $(Mustache.to_html(template, templateData));
					$("#tbd_task").append($html);

				} else if (item.type == 1) {
					//加分项
					// $("#tbd_pluse").html('');

					template = "<tr><input type='hidden' id=pluse_termId name=pluse_termId value='{{termId}}'><td class='span3' style='text-align:center;width:40%;word-wrap:break-word;vertical-align:middle;'>" +
						"<input type='text' id='pluse_term' name='pluse_term' value='{{term}}' class='perAdd-input' onfocus=\"javascript:this.style.background='#FFFFFF';\" onblur=\"javascript:this.style.background='transparent';\"/></td>" +
						"<td class='span3' style='text-align:center;width:40%;word-wrap:break-word;vertical-align:middle;'>" +
						"<input type='text' id='pluse_content' name='pluse_content' value='{{content}}'  class='perAdd-input'  onfocus=\"javascript:this.style.background='#FFFFFF';\" onblur=\"javascript:this.style.background='transparent';\"/></td>" +
						"<td class='span2 hidden-480' style='text-align:center;width:10%;word-wrap:break-word;vertical-align:middle;'>" +
						"<input type='text' id='pluse_score' name='pluse_score' value='{{score}}' class='perAdd-input'onfocus=\"javascript:this.style.background='#FFFFFF';\" onblur=\"javascript:this.style.background='transparent';\" /></td>" +
						"<td class='span2' style='text-align:center;width:10%;word-wrap:break-word;vertical-align:middle;'>" +
						"<i style='cursor:pointer;' id='pluse_delIcon' name='pluse_delIcon' class='icon-trash  bigger-150'></i></td></tr>";

					var $html = $(Mustache.to_html(template, templateData));
					$("#tbd_pluse").append($html);

					$html.find('#pluse_delIcon').click({
						html: $html
					}, function(e) {
						var $html = $(e.data.html);
						var termId = $html.find('#pluse_termId').val();
						var delTerm = $html.find('#pluse_term').val();

						bootbox.confirm("确定删除加分项【" + delTerm + "】吗？", function(result) {
							if (!result) {
								return;
							} else {

								delTermArr.push(termId);

								$html.remove();
							}
						});
					});

				} else {
					//内容及标准

					// $("#tbd_professional").html('');
					template = "<tr><input type=hidden id=professional_termId name=professional_termId value='{{termId}}'><td class='span3' style='text-align:center;width:30%;word-wrap:break-word;vertical-align:middle;' id='professional_term' name='professional_term'>{{term}}</td>" +
						"<td class='span3' style='text-align:center;width:10%;word-wrap:break-word;vertical-align:middle;' id='professional_weight' name='professional_weight'>{{weight}}</td>" +
						"<td class='span2 hidden-480' style='text-align:center;width:40%;word-wrap:break-word;vertical-align:middle;'>" +
						"<input type='text' id='professional_completion' name='professional_completion'  class='perAdd-input'onfocus=\"javascript:this.style.background='#FFFFFF';\" onblur=\"javascript:this.style.background='transparent';\" value='{{completion}}'></td>" +
						"<td class='span2 hidden-480' style='text-align:center;width:10%;word-wrap:break-word;vertical-align:middle;'>" +
						"<input type='text' id='professional_score' name='professional_score' value='{{score}}' class='perAdd-input'onfocus=\"javascript:this.style.background='#FFFFFF';\" onblur=\"javascript:this.style.background='transparent';\" /></td></tr>";


					var $html = $(Mustache.to_html(template, templateData));
					$("#tbd_professional").append($html);
				}
			});
		} else {
			return;
		}

	};

	//点击保存按钮
	$("#saveBtn").click(function() {
		var sendData = buildModel();
		var perfState = $("#perfState").val();
		if (perfState * 1 == 2) {
			bootbox.alert("已确认该绩效,不能保存！");
			return;
		}
		// console.info(sendData);
		sendData.deleteItems = delTermArr;
		// console.info("delTermArr--:", delTermArr);
		// return;
		sendData.perfId = $("#getPerfId").val();
		if (isNaN(sendData.score)) {
			bootbox.alert("请打分！");
			return;
		}
		if (sendData.scoreFlag) {
			bootbox.alert("每项得分区间为0-100分！");
			return;
		}
		if (!sendData.lengthCheck) {
			bootbox.alert("填写内容不得超过120字！");
			return;
		}
		// if(sendData.level != "B" && sendData.comment == "") {
		// 	$("#warnMsg").css("display","block");
		// 	return;
		// }
		sendData.operation = "审核";
		$.ajax({
			url: '/api/performance',
			type: "put",
			data: sendData,
			success: function(result) {
				if (result == 'noPrivilege') {
					bootbox.alert('您没有权限,操作失败！');
					return;
				}
				bootbox.alert(result, function() {
					var hisPage = $("#hisPage").val();
					window.location.href = "/performanceAudit?hisPage=" + hisPage;
					// window.location.href = document.referrer;
				});

			},
			error: function(result) {
				bootbox.alert("绩效信息保存失败！");
			}
		});
	});


	var getOrgParents = function(orgId, type) {
		$.ajax({
			url: '/api/organizations/getParents/' + orgId + '?',
			type: 'get',
			data: {'_t': new Date().getTime()},
			success: function(result) {
				// console.info(result);
				var parentString = "";
				for (var i = result.length - 1; i >= 0; i--) {
					if (i != 0) {
						if (result[i].orgName == "分公司") {
							continue;
						} else {
							parentString += result[i].orgName + "/";
						}

					} else {
						parentString += result[i].orgName;
					}
				}
				if (type == 1) {
					$("#projectDept").val(parentString);
					$("#preDeptId").val(result[0].id);
				} else {
					$("#department").val(parentString);
					$("#deptId").val(result[0].id);
				}


			}
		});
	};

	var buildModel = function() {
		// var assessmentPersonId = $("#assessmentid").val();//考核人id
		// var assessmentPer = $("#assessmentPerson").val();//考核人姓名
		var employeeId = $("#employeeid").val(); //被考核人id
		var employee = $("#employee").val(); //被考核人姓名
		var perfDate = $("#perfDate").val(); //审核时间
		var departmentId = $("#deptId").val();
		// var comment = $("#comment").val();
		var preDeptId = $("#preDeptId").val() == "" ? 0 : $("#preDeptId").val();
		var project = $("#project").val();
		// console.info("comment:",$("#comment").val());
		var scoreFlag = false; //判断每项得分是否超过一百分或者小于0

		var basicItems = []; //新增绩效项
		var updateItems = []; //更新绩效项
		var perfScore = 0;
		var basicScore = 0;
		var professionalScore = 0;
		var plusScore = 0;
		var lengthCheck = true;
		// var sumWeight_professonal = 0;

		//工作事项
		var termArr = $("td[name='term']");
		var contentArr = $("td[name='content']");
		var weightArr = $("td[name='weight']");
		var termIdArr = $("input[name='termId']");
		var completionArr = $("input[name='completion']");
		var completionCheck = true;
		var scoreArr = $("input[name='score']");
		termArr.each(function(i) {
			var completion = $(completionArr[i]).val().replace(/(^\s*)|(\s*$)/g, "");
			if (completion == "") {
				completionCheck = false;
			}
			if (completion.length > 120) {
				lengthCheck = false;
			}
			var score = $(scoreArr[i]).val();
			var weight = $(weightArr[i]).html().replace(/(^\s*)|(\s*$)/g, "");
			var itemData = {
				termId: $(termIdArr[i]).val(),
				term: $(termArr[i]).html().replace(/(^\s*)|(\s*$)/g, ""),
				content: $(contentArr[i]).html().replace(/(^\s*)|(\s*$)/g, ""),
				weight: parseFloat(weight),
				completion: completion,
				score: score,
				type: 0,
				state: 1,
				assPersonId: empId
			};
			if (score > 100 || score < 0) {
				scoreFlag = true;
			}
			basicScore += parseFloat(score) * parseFloat(weight) / 100;
			updateItems.push(itemData);
		});

		//加分项
		var plus_termArr = $("input[name='pluse_term']");
		var plus_contentArr = $("input[name='pluse_content']");
		var plus_termIdArr = $("input[name='pluse_termId']");
		var plus_scoreArr = $("input[name='pluse_score']");
		var plusCheck = true;
		plus_termArr.each(function(i) {
			var plus_term = $(plus_termArr[i]).val().replace(/(^\s*)|(\s*$)/g, "");
			var plus_content = $(plus_contentArr[i]).val().replace(/(^\s*)|(\s*$)/g, "");
			var plus_score = $(plus_scoreArr[i]).val().replace(/(^\s*)|(\s*$)/g, "");

			if (plus_term == "" && plus_content == "" && plus_score == "") {

			} else {
				if (plus_term == "" || plus_content == "" || plus_score == "") {
					plusCheck = false;
				}
				if (plus_term.length > 120 || plus_content.length > 120 || plus_score.length > 120) {
					lengthCheck = false;
				}
				var plus_term = $(plus_termArr[i]).val();
				if (plus_term != null && plus_term != "") {
					var plusItem = {
						term: plus_term,
						content: plus_content,
						score: plus_score,
						type: 1,
						state: 1,
						assPersonId: empId
					};
					plusScore += parseFloat($(plus_scoreArr[i]).val());
					var plus_termId = $(plus_termIdArr[i]).val();
					if (plus_termId != null && plus_termId != "") {
						plusItem.termId = plus_termId;
						updateItems.push(plusItem);
					} else {
						basicItems.push(plusItem);
					}
				}
			}
		});
		var professionalCheck = true;
		if (flag) {
			//内容及标准
			var professional_termArr = $("td[name='professional_term']");
			var professional_weightArr = $("td[name='professional_weight']");
			var professional_termIdArr = $("input[name='professional_termId']");
			var professional_completionArr = $("input[name='professional_completion']");
			var professional_scoreArr = $("input[name='professional_score']");


			professional_termArr.each(function(i) {
				var professional_completion = $(professional_completionArr[i]).val().replace(/(^\s*)|(\s*$)/g, "");
				if (professional_completion == "") {
					professionalCheck = false;
				}
				if(professional_completion.length>120){
					lengthCheck=false;
				}
				var professional_weight = $(professional_weightArr[i]).html().replace(/(^\s*)|(\s*$)/g, "");
				var professional_score = $(professional_scoreArr[i]).val();
				// console.info((professional_score == ""));
				var professionalItem = {
					term: $(professional_termArr[i]).html().replace(/(^\s*)|(\s*$)/g, ""),
					weight: parseFloat(professional_weight),
					completion: professional_completion,
					score: professional_score,
					type: 2,
					state: 1,
					assPersonId: empId
				};
				if (professional_score > 100 || professional_score < 0) {
					scoreFlag = true;
				}
				// sumWeight_professonal += professional_weight;
				professionalScore += parseFloat(professional_score) * parseFloat(professional_weight) / 100;

				var professional_termId = $(professional_termIdArr[i]).val();
				// console.info("professional_termId:",professional_termId);
				if (professional_termId != null && professional_termId != "") {
					professionalItem.termId = professional_termId;
					updateItems.push(professionalItem);
				} else {
					basicItems.push(professionalItem);
				}
			});
		}
		if (!completionCheck) {
			bootbox.alert("工作事项的完成情况不能为空！");
			return;
		}
		if (!plusCheck) {
			bootbox.alert("请完善加分项信息！");
			return;
		}

		//加分项总和不能超过20分
		if (plusScore > 20) {
			bootbox.alert("加分项总和不能超过20分！");
			return;
			// plusScore = 20;
		}
		if (!professionalCheck) {
			bootbox.alert("职业化评价的完成情况不能为空！");
			return;
		}
		// console.info("basicScore=" + basicScore + "--plusScore=" + plusScore + "--professionalScore=" + professionalScore);
		perfScore = (basicScore * 0.7) + plusScore + (professionalScore * 0.3);

		var performanceData = {
			basicItems: basicItems,
			updateItems: updateItems,
			// assessmentPersonId: assessmentPersonId,
			employeeId: employeeId,
			perfDate: perfDate,
			departmentId: departmentId,
			score: Math.round(perfScore * 100) / 100,
			// level: level,
			// comment: comment,
			preDeptId: preDeptId,
			project: project,
			scoreFlag: scoreFlag,
			lengthCheck:lengthCheck,
			basicScore : Math.round(basicScore * 100) / 100
		};


		return performanceData;
	};

    //绩效任务及目标部分权重分
    $("#count").click(function() {
    	var score = buildModel().score;
    	// console.info(basicScore);
    	$("#msg").css("display", "block");
    	$("#msgScore").html(score + "分");
    });

});